from itertools import islice


def convert_args(start, stop=-1, step=-1, length=None):
    if stop == -1 and step == -1:
        stop = start
        start = 0

    if stop is None or stop == -1:
        stop = length

    if step == -1:
        step = 1

    return start, stop, step


def slice_length(*args):
    s = slice(*args)
    start = s.start or 0
    stop = s.stop
    if stop is None:
        return None
    return len(xrange(start, stop, s.step or 1))


class countedslice(object):
    def __init__(self, itr, start, end=None, step=None):
        slc = slice(start, end, step)
        self._itr = islice(itr, slc.start, slc.stop, slc.step)
        self._length = slice_length(start, end, step)
        self.dirty = False

    def __iter__(self):
        if self.dirty:
            raise ValueError('already iterated')
        self.dirty = True
        return self._itr

    def __len__(self):
        if not self.dirty and self._length is not None:
            return self._length

        raise TypeError()

